package main

import (
	"fmt"
	"github.com/hashicorp/consul/api"
	"io/ioutil"
	"net/http"
	"strconv"
)

// register service
func registerService() {
	cfg := api.DefaultConfig()

	client, err := api.NewClient(cfg)
	if err != nil {
		panic(err)
		return
	}

	check := &api.AgentServiceCheck{
		HTTP:                           "http://10.0.0.67:8081/health",
		Timeout:                        "5s",
		Interval:                       "10s",
		DeregisterCriticalServiceAfter: "5s",
	}

	reg := &api.AgentServiceRegistration{
		ID:      "test1",
		Name:    "test1",
		Port:    8081,
		Tags:    []string{"tag1", "tag2"},
		Address: "127.0.0.1",
		Check:   check,
	}

	err = client.Agent().ServiceRegister(reg)
	if err != nil {
		panic(err)
		return
	}

	fmt.Println("register successful...")
}

// deRegister service
func deRegisterService(sId string) {
	cfg := api.DefaultConfig()

	client, err := api.NewClient(cfg)
	if err != nil {
		panic(err)
		return
	}

	err = client.Agent().ServiceDeregister(sId)
	if err != nil {
		panic(err)
		return
	}
}

// getAllService
func getAllService() []string {
	serviceSlice := make([]string, 0)
	cfg := api.DefaultConfig()

	client, err := api.NewClient(cfg)
	if err != nil {
		panic(err)
		return serviceSlice
	}

	services, err := client.Agent().Services()
	if err != nil {
		panic(err)
		return serviceSlice
	}

	for k := range services {
		serviceSlice = append(serviceSlice, k)
	}

	return serviceSlice

}

// getServiceByFilter
func getServiceByFilter(filter string) string {
	cfg := api.DefaultConfig()

	client, err := api.NewClient(cfg)

	if err != nil {
		panic(err)
	}

	service, err := client.Agent().ServicesWithFilter(fmt.Sprintf(`Service == "%s"`, filter))
	if err != nil {
		panic(err)
	}

	var url string

	for _, s := range service {
		url = "http://" + s.Address + ":" + strconv.Itoa(s.Port)
	}

	return url

}

// reset all service
func resetAllService() {
	fmt.Println("start reset all service...")
	cfg := api.DefaultConfig()

	client, err := api.NewClient(cfg)
	if err != nil {
		panic(err)
		return
	}

	services, err := client.Agent().Services()
	if err != nil {
		panic(err)
		return
	}

	for s := range services {
		deRegisterService(s)
	}

	fmt.Println("reset all service finish...")
}

func main() {
	//registerService()
	//deRegisterService()
	//getAllService()
	//resetAllService()
	resp, _ := http.Get(getServiceByFilter("test1") + "/info")
	defer resp.Body.Close()

	fmt.Println(resp.StatusCode)
	data, _ := ioutil.ReadAll(resp.Body)
	fmt.Println(string(data))
}
